package com.linjacy.httpproject.filter;

import com.linjacy.httpproject.component.MyBootContentScanHandler;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@Component
public class MyBootFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //在这里过滤请求转发到需要的controller
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        String requestURI = httpServletRequest.getRequestURI();
        Method method = MyBootContentScanHandler.getTheInvokeMethod(requestURI);
        if(method != null){
            Class<?> declaringClass = method.getDeclaringClass();
            Object invoke = method.invoke(declaringClass.newInstance());
            System.out.println(invoke);
            httpServletResponse.getOutputStream()
                    .write(invoke.toString().getBytes());
        }
        chain.doFilter(httpServletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {

    }
}
